package com.gitee.wsl.android.ui.signature.pan

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF

import com.gitee.wsl.common.ui.base.ControlPoint
import kotlin.math.hypot

/**
 * 钢笔
 *
 * @since 2018/06/15
 * @author king
 */
class SteelPen : BasePen() {
    override fun doPreDraw(canvas: Canvas) {
        for (i in 1 until mHWPointList.size) {
            val point = mHWPointList[i]
            drawToPoint(canvas, point, mPaint!!)
            mCurPoint = point
        }
    }

    override fun doMove(f: Float) {
        val steps = 1 + f.toInt() / STEP_FACTOR
        val step = 1.0f / steps
        var t = 0.0f
        while (t < 1.0f) {
            val point: ControlPoint = mBezier.getPoint(t)
            mHWPointList.add(point)
            t += step
        }
    }

    override fun doDraw(canvas: Canvas, point: ControlPoint, paint: Paint) {
        drawLine(
            canvas,
            mCurPoint!!.x,
            mCurPoint!!.y,
            mCurPoint!!.width,
            point.x,
            point.y,
            point.width,
            paint
        )
    }

    /**
     * 绘制方法，实现笔锋效果
     */
    private fun drawLine(
        canvas: Canvas,
        x0: Float,
        y0: Float,
        w0: Float,
        x1: Float,
        y1: Float,
        w1: Float,
        paint: Paint
    ) {
        //求两个数字的平方根 x的平方+y的平方在开方记得X的平方+y的平方=1，这就是一个园
        val curDis = hypot(x0 - x1, y0 - y1)
        val steps: Int
        //绘制的笔的宽度是多少，绘制多少个椭圆
        steps = if (paint.strokeWidth < 6) {
            1 + (curDis / 2).toInt()
        } else if (paint.strokeWidth > 60) {
            1 + (curDis / 4).toInt()
        } else {
            1 + (curDis / 3).toInt()
        }
        val deltaX = (x1 - x0) / steps
        val deltaY = (y1 - y0) / steps
        val deltaW = (w1 - w0) / steps
        var x = x0
        var y = y0
        var w = w0
        for (i in 0 until steps) {
            val oval = RectF()
            val top = (y - w / 2.0f)
            val left = (x - w / 4.0f)
            val right = (x + w / 4.0f)
            val bottom = (y + w / 2.0f)
            oval[left, top, right] = bottom
            //最基本的实现，通过点控制线，绘制椭圆
            canvas.drawOval(oval, paint)
            x += deltaX
            y += deltaY
            w += deltaW
        }
    }
}
